######################################################################
# Time-stamp: <2005-08-11 23:22:52 patrick>
######################################################################
package EP::EPC::Core::Sequence_Logo;

use strict;

use EP::Config;
use EP::Common;
use EP::Common::General;
use EP::Common::Error qw/:try/;

use EP::EPC::Core;
use EP::EPC::Core::Component;

use TFBS::PatternGen::SimplePFM;

use CGI qw/:standard/;

use Carp;
use Carp qw (cluck);

use File::Temp;
use File::Basename;

our @ISA = qw ( EP::EPC::Core::Component );

# sub: process_component
#   Processes the Sequence_Logo component.
#   It expects the query parameters sequences (a set of aligned sequences) or profile (a sequence profile) to be set.
# returns:
#   OK if everything went fine
sub process_component {
    my $self = shift;

    print STDERR "Working on sequence logo component";
    my $result = $self->_visualize_patterns ();

    my $dataset_folder_path = $EP::Config::h->{EPNG_USRDATA_PATH} . "/" . $self->{src_dataset}->folder->location;
    my $output_www_base = $EP::Config::h->{EPNG_USRDATA_URL} . "/" . $self->{src_dataset}->folder->location . "/";
    
    my $htmlfile = new File::Temp ( DIR => $dataset_folder_path, SUFFIX => ".html", UNLINK => 0 );
    my $htmlfile_url = $output_www_base . basename( $htmlfile );
    
    print $htmlfile $result;
    close $htmlfile;

    my $process_result = { html => $htmlfile_url,
			   src_dataset_id => $self->{src_dataset}->id,
			   dst_dataset_id => $self->{src_dataset}->id
			   }; # HACK: produce HTML output and place it all directly in <html></html> as a result!

    $self->{CD}->{process_result} = $process_result;
    return $self->record_analysis_history ();
}

sub _visualize_patterns {
    my $self = shift;
    my (@sequences, $pfm);

    print STDERR "Working inside visualize_patterns";
    throw EP::Common::Error ( -value => AFFY_TRANSFORM_RAW_DATA ) if $self->{src_dataset}->type eq "affy";
    
    if ( $self->{query}->param('sequences') !~ /^\s*$/ ) {
	# use input sequences to generate sequence logo

	my $sequences = $self->{query}->param('sequences');
	$sequences =~ s/^\s+|\s+$//g;   # get rid of spaces
	$sequences =~ s/\r\n|\n|\r/ /g; # get rid of newlines
	@sequences = split /\s+/, $sequences;

	my $pattern_gen = TFBS::PatternGen::SimplePFM->new( -seq_list => \@sequences );
	$pfm = $pattern_gen->pattern();
    } elsif ( $self->{query}->param('profile') !~ /^\s*$/ ) {
	# use sequence profile to generate sequence logo
	
    } else {
	# no input data !
	throw EP::Common::Error( -text => "No appropriate input given!" );
    }

    $self->{session}->status( "Generating Sequence Logo ..." );
    
    my $rand = "$$" . rand(100);
    my $imageFile = $self->{src_dataset}->filename . ".vis." . $rand . ".png";
    if ( ! $pfm->draw_logo( -file => $EP::Config::h->{EPNG_USRDATA_PATH} . "/" . 
			    $self->{src_dataset}->folder->location . "/" . $imageFile,
			    -xsize => 300,
			    -draw_error_bars => $self->{query}->param('error_bars') ) ) {
	throw EP::Common::Error( -text => "Unable to draw Sequence Logo" );
    }

    my $HTML_OUTPUT = start_html( -title => "Sequence Logo Visualization",
				  -target => "_blank",
				  -bgcolor => "white"
				  );
    $HTML_OUTPUT .= h2( { -align => "center" },
			"Sequence Logo Visualization" );
    
    $HTML_OUTPUT .= table( { -border => 1, 
			     -align => "center", 
			     -cellspacing => 0,
			     -cellpadding => 1 },
			   Tr( { -align => "center" },
			       [
				th( [ "Sequences", 
				      "PFM", 
				      "Total IC",
				      "Sequence Logo" ] ),
				td( [ "<small>" . join( "<br>", @sequences ) . "</small>",
				      "<pre>" . $pfm->prettyprint . "</pre>", 
				      sprintf( "%2.2f", $pfm->to_ICM->total_ic ),
				      img( { -src => $EP::Config::h->{EPNG_USRDATA_URL} . "/" . 
						 $self->{src_dataset}->folder->location . "/" . $imageFile,
					     -border => 0,
					     -width => 300 } ) ] )
				] )
			   );

    return $HTML_OUTPUT;
}

1;
